package com.example.sxt_practise.java并发编程;

import java.util.Objects;

/**
 * @author gaofeng
 * date 2022年02月15日 21:47
 */
public class GuardedObject {

    /**
     * 用来区分Guarded Object
     */
    private int id ;

    public GuardedObject(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    /**
     * /结果
     */
    private Object response ;

    /**
     * 获取结果
     * @author gaofeng
     * @date  2022/2/15 21:59
     * @param timeOut 等待时间
     * @return java.lang.Object
     */
    public Object getResponse(long timeOut) {
        long beginTime = System.currentTimeMillis() ;
        long parseTime = 0 ;
        while (Objects.isNull(response)) {
            long waitTime = timeOut - parseTime ;
            if (parseTime >= timeOut) {
                break;
            }
            synchronized (this) {
                try {
                    //this.wait(timeOut); 存在虚假唤醒
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            parseTime = System.currentTimeMillis() - beginTime ;
        }
        return response ;
    }

    /**
     * 产生结果. 当另一个线程执行结束,将返回值作为结果传给当前线程,该线程停止等待被唤醒
     * @author gaofeng
     * @date  2022/2/15 21:59
     * @param
     * @param response
     * @return
     */
    public void complete(Object response) {
        synchronized (this) {
            this.response = response ;
            this.notifyAll();
        }
    }
}
